<template>
  <Modal
    :open="visible"
    title="资源能力管理"
    width="1200px"
    :footer="null"
    :destroy-on-close="true"
    @update:open="(val) => emit('update:visible', val)"
  >
    <div class="capability-manager-v2">
      <!-- 顶部概览 -->
      <div class="overview-section">
        <div class="resource-info">
          <IconifyIcon
            :icon="resource?.icon || 'ant-design:appstore-outlined'"
            class="resource-icon"
          />
          <div class="resource-details">
            <h3>{{ resource?.name }}</h3>
            <p>{{ resource?.description }}</p>
          </div>
        </div>
        <div class="capability-stats">
          <div class="stat-item">
            <div class="stat-number">{{ enabledCapabilitiesCount }}</div>
            <div class="stat-label">已启用能力</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ totalCapabilitiesCount }}</div>
            <div class="stat-label">总能力数</div>
          </div>
        </div>
      </div>

      <!-- 能力定义区域 -->
      <div class="capability-definition-area">
        <div class="left-panel">
          <!-- 能力模板库 -->
          <div class="capability-templates">
            <h4>📚 能力模板库</h4>
            <div class="template-categories">
              <Tabs v-model="activeCategory" type="card" size="small">
                <TabPane key="business" tab="业务能力">
                  <div class="template-list">
                    <div
                      v-for="template in businessTemplates"
                      :key="template.id"
                      class="template-item"
                      @click="addCapabilityFromTemplate(template)"
                    >
                      <div class="template-icon">
                        <IconifyIcon :icon="template.icon" />
                      </div>
                      <div class="template-info">
                        <div class="template-name">{{ template.name }}</div>
                        <div class="template-desc">
                          {{ template.description }}
                        </div>
                      </div>
                      <Button type="link" size="small">
                        <IconifyIcon icon="ant-design:plus-outlined" />
                      </Button>
                    </div>
                  </div>
                </TabPane>
                <TabPane key="technical" tab="技术能力">
                  <div class="template-list">
                    <div
                      v-for="template in technicalTemplates"
                      :key="template.id"
                      class="template-item"
                      @click="addCapabilityFromTemplate(template)"
                    >
                      <div class="template-icon">
                        <IconifyIcon :icon="template.icon" />
                      </div>
                      <div class="template-info">
                        <div class="template-name">{{ template.name }}</div>
                        <div class="template-desc">
                          {{ template.description }}
                        </div>
                      </div>
                      <Button type="link" size="small">
                        <IconifyIcon icon="ant-design:plus-outlined" />
                      </Button>
                    </div>
                  </div>
                </TabPane>
                <TabPane key="custom" tab="自定义能力">
                  <div class="custom-capability-form">
                    <Form layout="vertical" size="small">
                      <FormItem label="能力名称">
                        <Input
                          v-model="customCapability.name"
                          placeholder="输入能力名称"
                        />
                      </FormItem>
                      <FormItem label="能力描述">
                        <Textarea
                          v-model="customCapability.description"
                          placeholder="描述能力功能"
                        />
                      </FormItem>
                      <FormItem label="能力类型">
                        <Select
                          v-model="customCapability.type"
                          placeholder="选择能力类型"
                        >
                          <SelectOption value="api">API接口</SelectOption>
                          <SelectOption value="service">服务调用</SelectOption>
                          <SelectOption value="workflow">工作流</SelectOption>
                          <SelectOption value="rule">规则引擎</SelectOption>
                        </Select>
                      </FormItem>
                      <Button type="primary" @click="addCustomCapability" block>
                        创建自定义能力
                      </Button>
                    </Form>
                  </div>
                </TabPane>
              </Tabs>
            </div>
          </div>
        </div>

        <div class="right-panel">
          <!-- 已配置能力 -->
          <div class="configured-capabilities">
            <div class="section-header">
              <h4>⚙️ 已配置能力</h4>
              <Button type="primary" size="small" @click="saveCapabilities">
                <IconifyIcon icon="ant-design:save-outlined" />
                保存配置
              </Button>
            </div>

            <div class="capabilities-grid">
              <div
                v-for="capability in configuredCapabilities"
                :key="capability.id"
                class="capability-card"
                :class="{ disabled: !capability.enabled }"
              >
                <div class="capability-header">
                  <div class="capability-icon">
                    <IconifyIcon :icon="capability.icon" />
                  </div>
                  <div class="capability-info">
                    <div class="capability-name">{{ capability.name }}</div>
                    <div class="capability-type">
                      {{ getTypeLabel(capability.type) }}
                    </div>
                  </div>
                  <div class="capability-actions">
                    <Switch
                      :checked="capability.enabled"
                      @update:checked="
                        (checked) => toggleCapability(capability.id, checked)
                      "
                      size="small"
                    />
                    <Button
                      type="link"
                      size="small"
                      @click="editCapability(capability)"
                    >
                      <IconifyIcon icon="ant-design:edit-outlined" />
                    </Button>
                    <Button
                      type="link"
                      size="small"
                      danger
                      @click="removeCapability(capability.id)"
                    >
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </Button>
                  </div>
                </div>

                <div class="capability-config">
                  <div class="config-row">
                    <span class="config-label">优先级:</span>
                    <InputNumber
                      :value="capability.priority"
                      @update:value="
                        (value) => updatePriority(capability.id, value)
                      "
                      :min="1"
                      :max="100"
                      size="small"
                      style="width: 80px"
                    />
                  </div>
                  <div class="config-row">
                    <span class="config-label">实现方式:</span>
                    <Tag
                      :color="
                        getImplementationColor(capability.implementation?.type)
                      "
                    >
                      {{
                        getImplementationLabel(capability.implementation?.type)
                      }}
                    </Tag>
                  </div>
                </div>

                <div class="capability-description">
                  {{ capability.description }}
                </div>
              </div>
            </div>

            <div v-if="configuredCapabilities.length === 0" class="empty-state">
              <IconifyIcon
                icon="ant-design:plus-circle-outlined"
                class="empty-icon"
              />
              <p>还没有配置任何能力</p>
              <p>从左侧模板库中选择能力添加到资源中</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 能力配置详情模态框 -->
      <Modal
        :open="configModalVisible"
        :title="`配置能力: ${currentCapability?.name}`"
        width="800px"
        @ok="saveCapabilityConfig"
        @cancel="configModalVisible = false"
      >
        <div class="capability-config-form">
          <Tabs v-model:active-key="configActiveTab" type="card">
            <TabPane key="basic" tab="基础配置">
              <Form layout="vertical">
                <FormItem label="能力名称">
                  <Input v-model="currentCapability.name" />
                </FormItem>
                <FormItem label="能力描述">
                  <Textarea v-model="currentCapability.description" />
                </FormItem>
                <FormItem label="启用状态">
                  <Switch v-model="currentCapability.enabled" />
                </FormItem>
                <FormItem label="优先级">
                  <InputNumber
                    v-model="currentCapability.priority"
                    :min="1"
                    :max="100"
                  />
                </FormItem>
              </Form>
            </TabPane>

            <TabPane key="implementation" tab="实现配置">
              <Form layout="vertical">
                <FormItem label="实现类型">
                  <Select v-model="currentCapability.implementation.type">
                    <SelectOption value="api">API接口</SelectOption>
                    <SelectOption value="service">服务调用</SelectOption>
                    <SelectOption value="workflow">工作流</SelectOption>
                    <SelectOption value="rule">规则引擎</SelectOption>
                  </Select>
                </FormItem>
                <FormItem label="实现地址">
                  <Input
                    v-model="currentCapability.implementation.url"
                    placeholder="API地址或服务名称"
                  />
                </FormItem>
                <FormItem label="请求方法">
                  <Select v-model="currentCapability.implementation.method">
                    <SelectOption value="GET">GET</SelectOption>
                    <SelectOption value="POST">POST</SelectOption>
                    <SelectOption value="PUT">PUT</SelectOption>
                    <SelectOption value="DELETE">DELETE</SelectOption>
                  </Select>
                </FormItem>
                <FormItem label="参数配置">
                  <div class="parameters-config">
                    <div
                      v-for="(param, index) in currentCapability.implementation
                        .parameters"
                      :key="index"
                      class="parameter-item"
                    >
                      <Input
                        v-model="param.name"
                        placeholder="参数名"
                        style="width: 120px"
                      />
                      <Select v-model="param.type" style="width: 100px">
                        <SelectOption value="string">字符串</SelectOption>
                        <SelectOption value="number">数字</SelectOption>
                        <SelectOption value="boolean">布尔值</SelectOption>
                        <SelectOption value="object">对象</SelectOption>
                      </Select>
                      <Input
                        v-model="param.default"
                        placeholder="默认值"
                        style="width: 120px"
                      />
                      <Button
                        type="link"
                        size="small"
                        danger
                        @click="removeParameter(index)"
                      >
                        <IconifyIcon icon="ant-design:delete-outlined" />
                      </Button>
                    </div>
                    <Button type="dashed" @click="addParameter" block>
                      <IconifyIcon icon="ant-design:plus-outlined" />
                      添加参数
                    </Button>
                  </div>
                </FormItem>
              </Form>
            </TabPane>

            <TabPane key="dependencies" tab="依赖关系">
              <div class="dependencies-config">
                <h5>前置依赖</h5>
                <div class="dependency-list">
                  <div
                    v-for="dep in currentCapability.dependencies.prerequisites"
                    :key="dep.id"
                    class="dependency-item"
                  >
                    <Select
                      v-model="dep.capabilityId"
                      placeholder="选择依赖能力"
                    >
                      <SelectOption
                        v-for="cap in availableDependencies"
                        :key="cap.id"
                        :value="cap.id"
                      >
                        {{ cap.name }}
                      </SelectOption>
                    </Select>
                    <Select v-model="dep.condition" style="width: 120px">
                      <SelectOption value="required">必需</SelectOption>
                      <SelectOption value="optional">可选</SelectOption>
                    </Select>
                    <Button
                      type="link"
                      size="small"
                      danger
                      @click="removeDependency(dep.id, 'prerequisites')"
                    >
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </Button>
                  </div>
                  <Button
                    type="dashed"
                    @click="addDependency('prerequisites')"
                    block
                  >
                    <IconifyIcon icon="ant-design:plus-outlined" />
                    添加前置依赖
                  </Button>
                </div>

                <h5>后置触发</h5>
                <div class="dependency-list">
                  <div
                    v-for="dep in currentCapability.dependencies.triggers"
                    :key="dep.id"
                    class="dependency-item"
                  >
                    <Select
                      v-model="dep.capabilityId"
                      placeholder="选择触发能力"
                    >
                      <SelectOption
                        v-for="cap in availableDependencies"
                        :key="cap.id"
                        :value="cap.id"
                      >
                        {{ cap.name }}
                      </SelectOption>
                    </Select>
                    <Select v-model="dep.condition" style="width: 120px">
                      <SelectOption value="always">总是</SelectOption>
                      <SelectOption value="success">成功时</SelectOption>
                      <SelectOption value="failure">失败时</SelectOption>
                    </Select>
                    <Button
                      type="link"
                      size="small"
                      danger
                      @click="removeDependency(dep.id, 'triggers')"
                    >
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </Button>
                  </div>
                  <Button
                    type="dashed"
                    @click="addDependency('triggers')"
                    block
                  >
                    <IconifyIcon icon="ant-design:plus-outlined" />
                    添加后置触发
                  </Button>
                </div>
              </div>
            </TabPane>
          </Tabs>
        </div>
      </Modal>
    </div>

    <!-- 能力配置模态框 -->
    <Modal
      v-model:open="configModalVisible"
      title="能力配置"
      width="800px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div v-if="currentCapability" class="capability-config-form">
        <Tabs v-model:active-key="configActiveTab">
          <TabPane key="basic" tab="基本信息">
            <Form layout="vertical">
              <FormItem label="能力名称">
                <Input v-model="currentCapability.name" />
              </FormItem>
              <FormItem label="能力描述">
                <Textarea v-model="currentCapability.description" :rows="3" />
              </FormItem>
              <FormItem label="能力类型">
                <Select v-model="currentCapability.type">
                  <SelectOption value="api">API接口</SelectOption>
                  <SelectOption value="service">服务调用</SelectOption>
                  <SelectOption value="workflow">工作流</SelectOption>
                  <SelectOption value="rule">规则引擎</SelectOption>
                </Select>
              </FormItem>
              <FormItem label="优先级">
                <InputNumber
                  v-model="currentCapability.priority"
                  :min="1"
                  :max="100"
                  style="width: 200px"
                />
              </FormItem>
            </Form>
          </TabPane>

          <TabPane key="implementation" tab="实现配置">
            <Form layout="vertical">
              <FormItem label="实现类型">
                <Select v-model="currentCapability.implementation.type">
                  <SelectOption value="bpm">BPM工作流</SelectOption>
                  <SelectOption value="orchestration">服务编排</SelectOption>
                  <SelectOption value="service">微服务</SelectOption>
                  <SelectOption value="rule">规则引擎</SelectOption>
                  <SelectOption value="api">API调用</SelectOption>
                </Select>
              </FormItem>
              <FormItem label="实现引用">
                <Input
                  v-model="currentCapability.implementation.ref"
                  placeholder="流程Key或URL"
                />
              </FormItem>
              <FormItem label="URL/服务地址">
                <Input v-model="currentCapability.implementation.url" />
              </FormItem>
              <FormItem label="请求方法">
                <Select v-model="currentCapability.implementation.method">
                  <SelectOption value="GET">GET</SelectOption>
                  <SelectOption value="POST">POST</SelectOption>
                  <SelectOption value="PUT">PUT</SelectOption>
                  <SelectOption value="DELETE">DELETE</SelectOption>
                </Select>
              </FormItem>
              <FormItem label="超时时间(秒)">
                <InputNumber
                  v-model="currentCapability.implementation.timeoutSec"
                  :min="1"
                  :max="3600"
                />
              </FormItem>

              <FormItem label="参数配置">
                <div class="parameters-config">
                  <div
                    v-for="(param, index) in currentCapability.implementation
                      .parameters"
                    :key="index"
                    class="parameter-item"
                  >
                    <Input
                      v-model="param.name"
                      placeholder="参数名"
                      style="width: 120px"
                    />
                    <Select v-model="param.type" style="width: 100px">
                      <SelectOption value="string">字符串</SelectOption>
                      <SelectOption value="number">数字</SelectOption>
                      <SelectOption value="boolean">布尔值</SelectOption>
                      <SelectOption value="object">对象</SelectOption>
                    </Select>
                    <Input
                      v-model="param.default"
                      placeholder="默认值"
                      style="width: 120px"
                    />
                    <Button
                      type="link"
                      size="small"
                      danger
                      @click="removeParameter(index)"
                    >
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </Button>
                  </div>
                  <Button type="dashed" @click="addParameter" block>
                    <IconifyIcon icon="ant-design:plus-outlined" />
                    添加参数
                  </Button>
                </div>
              </FormItem>
            </Form>

            <!-- SLA配置 -->
            <div class="sla-config">
              <h4>SLA配置</h4>
              <Form layout="vertical">
                <Row :gutter="16">
                  <Col :span="8">
                    <FormItem label="重试次数">
                      <InputNumber
                        v-model="currentCapability.sla.retry"
                        :min="0"
                        :max="10"
                      />
                    </FormItem>
                  </Col>
                  <Col :span="8">
                    <FormItem label="超时时间(秒)">
                      <InputNumber
                        v-model="currentCapability.sla.timeout"
                        :min="1"
                        :max="3600"
                      />
                    </FormItem>
                  </Col>
                  <Col :span="8">
                    <FormItem label="补偿流程">
                      <Input
                        v-model="currentCapability.sla.compensation"
                        placeholder="补偿流程Key"
                      />
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
          </TabPane>

          <TabPane key="preconditions" tab="前置约束">
            <div class="preconditions-config">
              <div class="section-header">
                <h4>前置约束</h4>
                <Button type="primary" size="small" @click="addPrecondition">
                  <IconifyIcon icon="ant-design:plus-outlined" />
                  添加约束
                </Button>
              </div>
              <div
                v-if="
                  !currentCapability.preconditions ||
                  currentCapability.preconditions.length === 0
                "
                class="empty-state"
              >
                <p>暂无前置约束，请添加约束</p>
              </div>
              <div v-else class="preconditions-list">
                <div
                  v-for="(
                    precondition, index
                  ) in currentCapability.preconditions"
                  :key="index"
                  class="precondition-item"
                >
                  <div class="precondition-header">
                    <span>约束 {{ index + 1 }}</span>
                    <Button
                      type="link"
                      size="small"
                      danger
                      @click="removePrecondition(index)"
                    >
                      <IconifyIcon icon="ant-design:delete-outlined" />
                      删除
                    </Button>
                  </div>
                  <Row :gutter="16">
                    <Col :span="8">
                      <FormItem label="约束类型">
                        <Select v-model="precondition.type">
                          <SelectOption value="stateIs">状态检查</SelectOption>
                          <SelectOption value="roleHas">角色权限</SelectOption>
                          <SelectOption value="expr">表达式</SelectOption>
                        </Select>
                      </FormItem>
                    </Col>
                    <Col :span="16">
                      <FormItem label="约束值">
                        <Input
                          v-model="precondition.value"
                          placeholder="约束值"
                        />
                      </FormItem>
                    </Col>
                  </Row>
                </div>
              </div>
            </div>
          </TabPane>

          <TabPane key="stateMachine" tab="状态机">
            <div class="state-machine-config">
              <h4>当前状态</h4>
              <div class="current-state">
                <Tag :color="getStateColor(resourceState)">
                  {{ resourceState }}
                </Tag>
                <Button
                  type="link"
                  size="small"
                  @click="showStateHistory"
                  style="margin-left: 12px"
                >
                  查看历史
                </Button>
              </div>

              <h4>允许的状态转换</h4>
              <div class="allowed-transitions">
                <div
                  v-for="transition in getAllowedTransitions()"
                  :key="transition.to"
                  class="transition-item"
                >
                  <Button
                    type="primary"
                    size="small"
                    @click="transitionTo(transition.to)"
                  >
                    {{ transition.from }} → {{ transition.to }} ({{
                      transition.by
                    }})
                  </Button>
                </div>
              </div>

              <h4>状态机定义</h4>
              <div class="state-machine-definition">
                <Form layout="vertical">
                  <FormItem label="状态列表">
                    <Select
                      v-model="stateMachine.states"
                      mode="tags"
                      placeholder="添加状态"
                    />
                  </FormItem>
                  <FormItem label="状态转换">
                    <div
                      v-for="(transition, index) in stateMachine.transitions"
                      :key="index"
                      class="transition-definition"
                    >
                      <Row :gutter="16">
                        <Col :span="6">
                          <Select
                            v-model="transition.from"
                            placeholder="从状态"
                          />
                        </Col>
                        <Col :span="6">
                          <Select
                            v-model="transition.to"
                            placeholder="到状态"
                          />
                        </Col>
                        <Col :span="6">
                          <Input
                            v-model="transition.by"
                            placeholder="触发行为"
                          />
                        </Col>
                        <Col :span="6">
                          <Button
                            @click="removeTransition(index)"
                            danger
                            size="small"
                            >删除</Button
                          >
                        </Col>
                      </Row>
                    </div>
                    <Button @click="addTransition" type="dashed" block>
                      <IconifyIcon icon="ant-design:plus-outlined" />
                      添加转换
                    </Button>
                  </FormItem>
                </Form>
              </div>
            </div>
          </TabPane>

          <TabPane key="events" tab="事件系统">
            <div class="events-config">
              <h4>事件定义</h4>
              <div class="event-definitions">
                <div
                  v-for="eventDef in eventDefs"
                  :key="eventDef.name"
                  class="event-definition"
                >
                  <div class="event-header">
                    <Tag color="blue">{{ eventDef.name }}</Tag>
                    <span class="event-channel">{{ eventDef.channel }}</span>
                  </div>
                  <div class="event-schema">
                    <h5>事件结构</h5>
                    <pre>{{
                      JSON.stringify(eventDef.payloadSchema, null, 2)
                    }}</pre>
                  </div>
                </div>
              </div>

              <h4>事件订阅</h4>
              <div class="event-subscriptions">
                <div
                  v-for="eventDef in eventDefs"
                  :key="eventDef.name"
                  class="subscription-item"
                >
                  <span>{{ eventDef.name }}</span>
                  <Button
                    v-if="!eventSubscriptions.has(eventDef.name)"
                    type="primary"
                    size="small"
                    @click="subscribeToEvent(eventDef.name)"
                  >
                    订阅
                  </Button>
                  <Button v-else type="default" size="small" disabled>
                    已订阅
                  </Button>
                </div>
              </div>

              <h4>发布事件</h4>
              <div class="event-publishing">
                <Form layout="vertical">
                  <FormItem label="选择事件">
                    <Select
                      v-model="selectedEvent"
                      placeholder="选择要发布的事件"
                    >
                      <SelectOption
                        v-for="eventDef in eventDefs"
                        :key="eventDef.name"
                        :value="eventDef.name"
                      >
                        {{ eventDef.name }}
                      </SelectOption>
                    </Select>
                  </FormItem>
                  <FormItem label="事件数据">
                    <Textarea
                      v-model="eventPayload"
                      :rows="6"
                      placeholder="输入JSON格式的事件数据"
                    />
                  </FormItem>
                  <Button
                    type="primary"
                    @click="publishSelectedEvent"
                    :disabled="!selectedEvent || !eventPayload"
                  >
                    发布事件
                  </Button>
                </Form>
              </div>
            </div>
          </TabPane>

          <TabPane key="behaviors" tab="行为执行">
            <div class="behaviors-config">
              <div class="behaviors-header">
                <h4>可用行为</h4>
                <div class="behaviors-actions">
                  <Button
                    @click="showWorkflowDesigner"
                    type="default"
                    size="small"
                  >
                    <IconifyIcon icon="ant-design:branches-outlined" />
                    工作流设计器
                  </Button>
                  <Button @click="showRuleEngine" type="default" size="small">
                    <IconifyIcon icon="ant-design:setting-outlined" />
                    规则引擎
                  </Button>
                  <Button
                    @click="showPerformanceMonitor"
                    type="default"
                    size="small"
                  >
                    <IconifyIcon icon="ant-design:dashboard-outlined" />
                    性能监控
                  </Button>
                </div>
              </div>
              <div class="behavior-list">
                <div
                  v-for="behavior in behaviorDefs"
                  :key="behavior.id"
                  class="behavior-item"
                >
                  <div class="behavior-header">
                    <h5>{{ behavior.name }}</h5>
                    <Tag :color="getImplementationColor(behavior.impl.type)">
                      {{ getImplementationLabel(behavior.impl.type) }}
                    </Tag>
                  </div>
                  <div class="behavior-details">
                    <p>{{ behavior.inputSchema?.description || '无描述' }}</p>
                    <div class="behavior-actions">
                      <Button
                        type="primary"
                        size="small"
                        @click="showBehaviorExecutionModal(behavior)"
                      >
                        执行
                      </Button>
                      <Button
                        type="default"
                        size="small"
                        @click="showBehaviorDetails(behavior)"
                      >
                        详情
                      </Button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </TabPane>

          <TabPane key="dependencies" tab="依赖关系">
            <div class="dependencies-config">
              <h5>前置依赖</h5>
              <div class="dependency-list">
                <div
                  v-for="dep in currentCapability.dependencies.prerequisites"
                  :key="dep.id"
                  class="dependency-item"
                >
                  <Select
                    v-model="dep.capabilityId"
                    placeholder="选择依赖能力"
                    style="width: 200px"
                  >
                    <SelectOption
                      v-for="cap in availableDependencies"
                      :key="cap.id"
                      :value="cap.id"
                    >
                      {{ cap.name }}
                    </SelectOption>
                  </Select>
                  <Select v-model="dep.condition" style="width: 120px">
                    <SelectOption value="required">必需</SelectOption>
                    <SelectOption value="optional">可选</SelectOption>
                  </Select>
                  <Button
                    type="link"
                    size="small"
                    danger
                    @click="removeDependency(dep.id, 'prerequisites')"
                  >
                    <IconifyIcon icon="ant-design:delete-outlined" />
                  </Button>
                </div>
                <Button
                  type="dashed"
                  @click="addDependency('prerequisites')"
                  block
                >
                  <IconifyIcon icon="ant-design:plus-outlined" />
                  添加前置依赖
                </Button>
              </div>

              <h5>后置触发</h5>
              <div class="dependency-list">
                <div
                  v-for="dep in currentCapability.dependencies.triggers"
                  :key="dep.id"
                  class="dependency-item"
                >
                  <Select
                    v-model="dep.capabilityId"
                    placeholder="选择触发能力"
                    style="width: 200px"
                  >
                    <SelectOption
                      v-for="cap in availableDependencies"
                      :key="cap.id"
                      :value="cap.id"
                    >
                      {{ cap.name }}
                    </SelectOption>
                  </Select>
                  <Select v-model="dep.condition" style="width: 120px">
                    <SelectOption value="always">总是</SelectOption>
                    <SelectOption value="success">成功时</SelectOption>
                    <SelectOption value="failure">失败时</SelectOption>
                  </Select>
                  <Button
                    type="link"
                    size="small"
                    danger
                    @click="removeDependency(dep.id, 'triggers')"
                  >
                    <IconifyIcon icon="ant-design:delete-outlined" />
                  </Button>
                </div>
                <Button type="dashed" @click="addDependency('triggers')" block>
                  <IconifyIcon icon="ant-design:plus-outlined" />
                  添加后置触发
                </Button>
              </div>
            </div>
          </TabPane>
        </Tabs>

        <div class="config-actions">
          <Button @click="configModalVisible = false">取消</Button>
          <Button type="primary" @click="saveCapabilityConfig">
            保存配置
          </Button>
        </div>
      </div>
    </Modal>

    <!-- 行为执行模态框 -->
    <Modal
      v-model:open="behaviorExecutionModalVisible"
      title="执行行为"
      width="600px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div v-if="currentBehavior" class="behavior-execution-form">
        <div class="behavior-info">
          <h4>{{ currentBehavior.name }}</h4>
          <p>{{ currentBehavior.inputSchema?.description || '无描述' }}</p>
        </div>

        <Form layout="vertical">
          <FormItem
            v-for="(prop, key) in currentBehavior.inputSchema?.properties"
            :key="key"
            :label="key"
            :required="currentBehavior.inputSchema?.required?.includes(key)"
          >
            <Input v-model="behaviorInput[key]" :placeholder="`输入 ${key}`" />
          </FormItem>
        </Form>

        <div class="execution-actions">
          <Button @click="behaviorExecutionModalVisible = false">取消</Button>
          <Button type="primary" @click="executeSelectedBehavior">
            执行行为
          </Button>
        </div>
      </div>
    </Modal>

    <!-- 状态历史模态框 -->
    <Modal
      v-model:open="stateHistoryModalVisible"
      title="状态历史"
      width="800px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div class="state-history-modal">
        <div v-if="stateHistory.length === 0" class="empty-state">
          <p>暂无状态历史记录</p>
        </div>
        <div v-else class="history-list">
          <div
            v-for="(record, index) in stateHistory"
            :key="index"
            class="history-item"
          >
            <div class="history-state">
              <Tag :color="getStateColor(record.state)">
                {{ record.state }}
              </Tag>
            </div>
            <div class="history-info">
              <div class="history-time">
                {{ new Date(record.timestamp).toLocaleString() }}
              </div>
              <div class="history-reason">
                {{ record.reason }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </Modal>

    <!-- 工作流设计器模态框 -->
    <!-- 工作流设计器抽屉 -->
    <WorkflowDrawer>
      <div style="height: calc(100vh - 120px); overflow: hidden">
        <RboWorkflowDesigner />
      </div>
    </WorkflowDrawer>

    <!-- 规则引擎抽屉 -->
    <RuleEngineDrawer>
      <div style="height: calc(100vh - 120px); overflow: hidden">
        <RboRuleEngine />
      </div>
    </RuleEngineDrawer>

    <!-- 性能监控抽屉 -->
    <PerformanceMonitorDrawer>
      <div style="height: calc(100vh - 120px); overflow: hidden">
        <PerformanceMonitor />
      </div>
    </PerformanceMonitorDrawer>

    <!-- 能力配置模态框 -->
    <CapabilityConfigModal
      v-model:visible="capabilityConfigVisible"
      :capability="currentEditingCapability"
      :resource="resource"
      @save="handleCapabilityConfigSave"
    />
  </Modal>
</template>

<script lang="ts" setup>
import {
  ref,
  reactive,
  computed,
  watch,
  h,
  nextTick,
  onMounted,
  onUnmounted,
} from 'vue';
import {
  Button,
  Tabs,
  TabPane,
  Form,
  FormItem,
  Input,
  Textarea,
  Select,
  SelectOption,
  Switch,
  InputNumber,
  Tag,
  message,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import { useVbenDrawer } from '@vben/common-ui';
import { getCapabilityTemplates } from '#/api/resource-center';
import { rboApi, type BehaviorDef, type EventDef } from '#/api/rbo-api';
import { CapabilityConfigModal } from '../../capability';
import RboWorkflowDesigner from '../../workflow-designer/index';
import RboRuleEngine from '../../capability/components/RboRuleEngine.vue';
import PerformanceMonitor from '../../capability/components/PerformanceMonitor.vue';
import ResourceCapabilityGuide from '../../guides/ResourceCapabilityGuide.vue';

// Props
const props = defineProps<{
  visible: boolean;
  resource?: any;
  editCapabilityId?: string; // 新增：要编辑的能力ID
}>();

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  success: [data: any]
}>();

// 抽屉相关
const [WorkflowDrawer, workflowDrawerApi] = useVbenDrawer({
  title: 'RBO工作流设计器',
  width: '90%',
  footer: false,
  closeOnClickModal: false,
  modal: false,
});

const [RuleEngineDrawer, ruleEngineDrawerApi] = useVbenDrawer({
  title: 'RBO规则引擎',
  width: '90%',
  footer: false,
  closeOnClickModal: false,
  modal: false,
});

const [PerformanceMonitorDrawer, performanceMonitorDrawerApi] = useVbenDrawer({
  title: 'RBO性能监控',
  width: '90%',
  footer: false,
  closeOnClickModal: false,
  modal: false,
});

// 响应式数据
const activeCategory = ref('business');
const configModalVisible = ref(false);
const configActiveTab = ref('basic');
const currentCapability = ref<any>(null);
const configuredCapabilities = ref<any[]>([]);
const customCapability = reactive({
  name: '',
  description: '',
  type: 'api',
});

// 能力模板库
const businessTemplates = ref<any[]>([]);
const technicalTemplates = ref<any[]>([]);

// 统一的mock数据引用（从后端mock服务获取）
// 备用数据已移至 apps/backend-mock/api/resource-center/capability-templates.get.ts
// 这里不再需要本地备用数据，统一使用mock服务提供的数据

// 状态机支持
const resourceState = ref('idle');
const stateMachine = ref({
  states: ['idle', 'reserved', 'occupied', 'cleaning', 'maintenance'],
  transitions: [
    { from: 'idle', to: 'reserved', by: 'reserve' },
    { from: 'reserved', to: 'idle', by: 'cancel' },
    { from: 'reserved', to: 'occupied', by: 'checkin' },
    { from: 'occupied', to: 'cleaning', by: 'checkout' },
    { from: 'cleaning', to: 'idle', by: 'finishCleaning' },
  ],
});

// 状态机方法
const getCurrentState = () => resourceState.value;
const getAllowedTransitions = () => {
  return stateMachine.value.transitions.filter((t) =>
    t.from.includes(resourceState.value),
  );
};
const canTransition = (toState: string) => {
  return getAllowedTransitions().some((t) => t.to === toState);
};
const transitionTo = (toState: string) => {
  if (canTransition(toState)) {
    resourceState.value = toState;
    return true;
  }
  return false;
};

// 事件系统支持
const eventDefs = ref<EventDef[]>([]);
const behaviorDefs = ref<BehaviorDef[]>([]);
const eventSubscriptions = ref<Map<string, string>>(new Map());

// 加载事件定义
const loadEventDefs = async () => {
  try {
    const events = await rboApi.getEventDefs('room');
    eventDefs.value = events;
  } catch (error) {
    console.error('加载事件定义失败:', error);
  }
};

// 加载行为定义
const loadBehaviorDefs = async () => {
  try {
    const behaviors = await rboApi.getBehaviors('room');
    behaviorDefs.value = behaviors;
  } catch (error) {
    console.error('加载行为定义失败:', error);
  }
};

// 发布事件
const publishEvent = async (
  eventName: string,
  payload: Record<string, any>,
) => {
  try {
    const result = await rboApi.publishEvent(
      eventName,
      'room',
      props.resource?.id || 'unknown',
      payload,
    );
    if (result.published) {
      message.success(`事件 ${eventName} 发布成功`);
    }
    return result;
  } catch (error) {
    console.error('发布事件失败:', error);
    message.error('发布事件失败');
    throw error;
  }
};

// 订阅事件
const subscribeToEvent = async (eventName: string) => {
  try {
    const result = await rboApi.subscribeToEvent(eventName, (event) => {
      console.log(`收到事件 ${eventName}:`, event);
      // 处理事件逻辑
      handleEvent(event);
    });
    eventSubscriptions.value.set(eventName, result.subscriptionId);
    message.success(`已订阅事件 ${eventName}`);
    return result;
  } catch (error) {
    console.error('订阅事件失败:', error);
    message.error('订阅事件失败');
    throw error;
  }
};

// 处理事件
const handleEvent = (event: any) => {
  switch (event.name) {
    case 'RoomReserved':
      // 处理房间预订事件
      console.log('房间已预订:', event.payload);
      break;
    case 'RoomCheckedIn':
      // 处理入住事件
      console.log('房间已入住:', event.payload);
      break;
    case 'RoomCheckedOut':
      // 处理退房事件
      console.log('房间已退房:', event.payload);
      break;
    default:
      console.log('未知事件:', event);
  }
};

// 执行行为
const executeBehavior = async (
  behaviorName: string,
  input: Record<string, any>,
) => {
  try {
    const result = await rboApi.invokeBehavior(
      'room',
      props.resource?.id || 'unknown',
      behaviorName,
      {
        input,
        context: {
          tenantId: 'default',
          userId: 'current-user',
          traceId: `trace_${Date.now()}`,
        },
      },
    );

    if (result.status === 'completed') {
      message.success(`行为 ${behaviorName} 执行成功`);
      // 更新资源状态
      if (result.state) {
        resourceState.value = result.state;
      }
    } else if (result.status === 'accepted') {
      message.info(`行为 ${behaviorName} 已接受，正在处理中`);
    } else {
      message.error(`行为 ${behaviorName} 执行失败`);
    }

    return result;
  } catch (error) {
    console.error('执行行为失败:', error);
    message.error('执行行为失败');
    throw error;
  }
};

// 性能优化：加载能力模板（带缓存）
const loadCapabilityTemplates = async () => {
  console.log('开始加载能力模板...');

  // 如果已经加载过，直接使用缓存
  if (templatesLoaded.value) {
    businessTemplates.value = cachedBusinessTemplates.value;
    technicalTemplates.value = cachedTechnicalTemplates.value;
    console.log('使用缓存的能力模板数据');
    return;
  }

  try {
    // 并行加载业务和技术能力模板
    const [businessData, technicalData] = await Promise.all([
      getCapabilityTemplates({ category: 'business' }),
      getCapabilityTemplates({ category: 'technical' }),
    ]);

    console.log('业务能力模板数据:', businessData);
    console.log('技术能力模板数据:', technicalData);

    // 处理业务能力模板数据
    if (businessData && Array.isArray(businessData)) {
      cachedBusinessTemplates.value = businessData;
      businessTemplates.value = businessData;
      console.log('业务能力模板加载成功，数量:', businessData.length);
    } else {
      console.warn('业务能力模板响应异常:', businessData);
      businessTemplates.value = [];
    }

    // 处理技术能力模板数据
    if (technicalData && Array.isArray(technicalData)) {
      cachedTechnicalTemplates.value = technicalData;
      technicalTemplates.value = technicalData;
      console.log('技术能力模板加载成功，数量:', technicalData.length);
    } else {
      console.warn('技术能力模板响应异常:', technicalData);
      technicalTemplates.value = [];
    }

    templatesLoaded.value = true;
    console.log('能力模板加载完成');
  } catch (error) {
    console.error('加载能力模板失败:', error);
    businessTemplates.value = [];
    technicalTemplates.value = [];
    throw error; // 重新抛出错误，让上层处理
  }
};

// 计算属性
const enabledCapabilitiesCount = computed(
  () => configuredCapabilities.value.filter((cap) => cap.enabled).length,
);

const totalCapabilitiesCount = computed(
  () => configuredCapabilities.value.length,
);

const availableDependencies = computed(() =>
  configuredCapabilities.value.filter(
    (cap) => cap.id !== currentCapability.value?.id,
  ),
);

// 性能优化：缓存能力模板数据
const cachedBusinessTemplates = ref<Array<any>>([]);
const cachedTechnicalTemplates = ref<Array<any>>([]);
const templatesLoaded = ref(false);

// 性能优化：防抖搜索
const searchKeyword = ref('');
const debouncedSearch = ref('');
let searchTimeout: NodeJS.Timeout | null = null;searchTimeoutsearchTimeout

// 性能优化：虚拟滚动相关
const virtualScrollConfig = {
  itemHeight: 60,
  visibleCount: 10,
  bufferSize: 5,
};

// 方法
const addCapabilityFromTemplate = (template: any) => {
  const capability = {
    id: `${template.id}_${Date.now()}`,
    name: template.name,
    description: template.description,
    icon: template.icon,
    type: template.type,
    enabled: true,
    priority: 50,
    implementation: {
      type: 'api',
      url: '',
      method: 'POST',
      parameters: [],
      ref: '',
      timeoutSec: 60,
      ...template.implementation,
    },
    dependencies: {
      prerequisites: [],
      triggers: [],
    },
    // 添加前置约束
    preconditions: [],
    // 添加SLA配置
    sla: {
      retry: 1,
      compensation: '',
      timeout: 60,
    },
  };

  configuredCapabilities.value.push(capability);
  message.success(`已添加能力: ${template.name}`);
};

const addCustomCapability = () => {
  if (!customCapability.name || !customCapability.description) {
    message.error('请填写完整的能力信息');
    return;
  }

  const capability = {
    id: `custom_${Date.now()}`,
    name: customCapability.name,
    description: customCapability.description,
    icon: 'ant-design:setting-outlined',
    type: customCapability.type,
    enabled: true,
    priority: 50,
    implementation: {
      type: customCapability.type,
      url: '',
      method: 'POST',
      parameters: [],
    },
    dependencies: {
      prerequisites: [],
      triggers: [],
    },
  };

  configuredCapabilities.value.push(capability);

  // 清空表单
  customCapability.name = '';
  customCapability.description = '';
  customCapability.type = 'api';

  message.success(`已创建自定义能力: ${capability.name}`);
};

const toggleCapability = (id: string, enabled: boolean) => {
  const capability = configuredCapabilities.value.find((cap) => cap.id === id);
  if (capability) {
    capability.enabled = enabled;
  }
};

const editCapability = (capability: any) => {
  // 确保所有必要的属性都存在
  currentCapability.value = {
    ...capability,
    implementation: {
      type: 'api',
      url: '',
      method: 'POST',
      parameters: [],
      ref: '',
      timeoutSec: 60,
      ...capability.implementation,
    },
    dependencies: {
      prerequisites: [],
      triggers: [],
      ...capability.dependencies,
    },
    // 添加前置约束
    preconditions: capability.preconditions || [],
    // 添加SLA配置
    sla: {
      retry: 1,
      compensation: '',
      timeout: 60,
      ...capability.sla,
    },
  };
  configModalVisible.value = true;
};

const removeCapability = (id: string) => {
  const index = configuredCapabilities.value.findIndex((cap) => cap.id === id);
  if (index > -1) {
    configuredCapabilities.value.splice(index, 1);
    message.success('已移除能力');
  }
};

const updatePriority = (id: string, priority: number) => {
  const capability = configuredCapabilities.value.find((cap) => cap.id === id);
  if (capability) {
    capability.priority = priority;
  }
};

const saveCapabilityConfig = () => {
  if (currentCapability.value) {
    const index = configuredCapabilities.value.findIndex(
      (cap) => cap.id === currentCapability.value.id,
    );
    if (index > -1) {
      configuredCapabilities.value[index] = { ...currentCapability.value };
    }
    configModalVisible.value = false;
    message.success('能力配置已保存');
  }
};

const addParameter = () => {
  if (currentCapability.value) {
    // 确保 implementation 对象存在
    if (!currentCapability.value.implementation) {
      currentCapability.value.implementation = {
        type: 'api',
        url: '',
        method: 'POST',
        parameters: [],
      };
    }
    // 确保 parameters 数组存在
    if (!currentCapability.value.implementation.parameters) {
      currentCapability.value.implementation.parameters = [];
    }

    currentCapability.value.implementation.parameters.push({
      name: '',
      type: 'string',
      default: '',
    });
  }
};

const removeParameter = (index: number) => {
  if (
    currentCapability.value &&
    currentCapability.value.implementation?.parameters
  ) {
    currentCapability.value.implementation.parameters.splice(index, 1);
  }
};

const addDependency = (type: 'prerequisites' | 'triggers') => {
  if (currentCapability.value) {
    // 确保 dependencies 对象存在
    if (!currentCapability.value.dependencies) {
      currentCapability.value.dependencies = {
        prerequisites: [],
        triggers: [],
      };
    }
    // 确保指定类型的依赖数组存在
    if (!currentCapability.value.dependencies[type]) {
      currentCapability.value.dependencies[type] = [];
    }

    currentCapability.value.dependencies[type].push({
      id: `dep_${Date.now()}`,
      capabilityId: '',
      condition: type === 'prerequisites' ? 'required' : 'always',
    });
  }
};

const removeDependency = (id: string, type: 'prerequisites' | 'triggers') => {
  if (currentCapability.value && currentCapability.value.dependencies?.[type]) {
    const index = currentCapability.value.dependencies[type].findIndex(
      (dep: any) => dep.id === id,
    );
    if (index > -1) {
      currentCapability.value.dependencies[type].splice(index, 1);
    }
  }
};

// 前置约束方法
const addPrecondition = () => {
  if (currentCapability.value) {
    if (!currentCapability.value.preconditions) {
      currentCapability.value.preconditions = [];
    }
    currentCapability.value.preconditions.push({
      type: 'stateIs',
      value: '',
      expression: '',
    });
  }
};

const removePrecondition = (index: number) => {
  if (currentCapability.value?.preconditions) {
    currentCapability.value.preconditions.splice(index, 1);
  }
};

// 实现配置方法
const updateImplementationConfig = (config: any) => {
  if (currentCapability.value) {
    currentCapability.value.implementation = {
      ...currentCapability.value.implementation,
      ...config,
    };
  }
};

// 状态机相关方法
const getStateColor = (state: string) => {
  const colors: Record<string, string> = {
    idle: 'green',
    reserved: 'blue',
    occupied: 'orange',
    cleaning: 'purple',
    maintenance: 'red',
  };
  return colors[state] || 'default';
};

// 状态历史相关
const stateHistory = ref<
  Array<{ state: string; timestamp: string; reason: string }>
>([]);
const stateHistoryModalVisible = ref(false);

// 高级功能相关
const workflowDesignerVisible = ref(false);
const ruleEngineVisible = ref(false);
const performanceMonitorVisible = ref(false);
const guideVisible = ref(false);

// 能力配置相关
const capabilityConfigVisible = ref(false);
const currentEditingCapability = ref<any>(null);

// 加载状态历史
const loadStateHistory = async () => {
  try {
    const history = await rboApi.getStateHistory(
      'room',
      props.resource?.id || 'unknown',
    );
    stateHistory.value = history;
  } catch (error) {
    console.error('加载状态历史失败:', error);
  }
};

// 显示状态历史
const showStateHistory = async () => {
  await loadStateHistory();
  stateHistoryModalVisible.value = true;
};

const addTransition = () => {
  stateMachine.value.transitions.push({
    from: '',
    to: '',
    by: '',
  });
};

const removeTransition = (index: number) => {
  stateMachine.value.transitions.splice(index, 1);
};

// 事件和行为执行相关的方法
const selectedEvent = ref('');
const eventPayload = ref('');

// 发布选中的事件
const publishSelectedEvent = async () => {
  if (!selectedEvent.value || !eventPayload.value) {
    message.error('请选择事件并输入事件数据');
    return;
  }

  try {
    const payload = JSON.parse(eventPayload.value);
    await publishEvent(selectedEvent.value, payload);
    // 清空表单
    selectedEvent.value = '';
    eventPayload.value = '';
  } catch (error) {
    if (error instanceof SyntaxError) {
      message.error('事件数据格式错误，请输入有效的JSON');
    } else {
      message.error('发布事件失败');
    }
  }
};

// 显示行为执行模态框
const behaviorExecutionModalVisible = ref(false);
const currentBehavior = ref<BehaviorDef | null>(null);
const behaviorInput = ref<Record<string, any>>({});

const showBehaviorExecutionModal = (behavior: BehaviorDef) => {
  currentBehavior.value = behavior;
  behaviorInput.value = {};
  behaviorExecutionModalVisible.value = true;
};

// 执行选中的行为
const executeSelectedBehavior = async () => {
  if (!currentBehavior.value) {
    message.error('未选择行为');
    return;
  }

  try {
    await executeBehavior(currentBehavior.value.name, behaviorInput.value);
    behaviorExecutionModalVisible.value = false;
    currentBehavior.value = null;
    behaviorInput.value = {};
  } catch (error) {
    message.error('执行行为失败');
  }
};

// 显示行为详情
const showBehaviorDetails = (behavior: BehaviorDef) => {
  Modal.info({
    title: `行为详情: ${behavior.name}`,
    width: 800,
    content: h('div', [
      h('h4', '输入参数'),
      h('pre', JSON.stringify(behavior.inputSchema, null, 2)),
      h('h4', '输出参数'),
      h('pre', JSON.stringify(behavior.outputSchema, null, 2)),
      h('h4', '前置约束'),
      h('pre', JSON.stringify(behavior.preconditions, null, 2)),
      h('h4', '实现配置'),
      h('pre', JSON.stringify(behavior.impl, null, 2)),
      h('h4', 'SLA配置'),
      h('pre', JSON.stringify(behavior.sla, null, 2)),
    ]),
  });
};

// 显示工作流设计器
const showWorkflowDesigner = () => {
  workflowDrawerApi.open();
};

// 显示规则引擎
const showRuleEngine = () => {
  ruleEngineDrawerApi.open();
};

// 显示性能监控
const showPerformanceMonitor = () => {
  performanceMonitorDrawerApi.open();
};

// 显示使用指南
const showGuide = () => {
  guideVisible.value = true;
};

// 打开能力配置模态框
const openCapabilityConfig = (capability: any) => {
  currentEditingCapability.value = capability;
  capabilityConfigVisible.value = true;
};

// 处理能力配置保存
const handleCapabilityConfigSave = (capability: any) => {
  // 更新已配置的能力列表
  const index = configuredCapabilities.value.findIndex(
    (cap) => cap.id === capability.id,
  );
  if (index !== -1) {
    configuredCapabilities.value[index] = capability;
  } else {
    configuredCapabilities.value.push(capability);
  }

  capabilityConfigVisible.value = false;
  currentEditingCapability.value = null;
  message.success('能力配置已保存');
};

// 性能优化：防抖搜索处理
const handleSearch = (value: string) => {
  searchKeyword.value = value;

  if (searchTimeout) {
    clearTimeout(searchTimeout);
  }

  searchTimeout = setTimeout(() => {
    debouncedSearch.value = value;
  }, 300);
};

// 性能优化：清理定时器
onUnmounted(() => {
  if (searchTimeout) {
    clearTimeout(searchTimeout);
  }
});

const saveCapabilities = () => {
  // 构建保存数据
  const capabilitiesData: Record<string, any> = {};
  configuredCapabilities.value.forEach((cap) => {
    capabilitiesData[cap.id] = {
      enabled: cap.enabled,
      priority: cap.priority,
      implementation: cap.implementation,
      dependencies: cap.dependencies,
    };
  });

  emit('success', capabilitiesData);
  message.success('能力配置已保存');
};

// 工具方法
const getTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    api: 'API接口',
    service: '服务调用',
    workflow: '工作流',
    rule: '规则引擎',
  };
  return labels[type] || type;
};

const getImplementationColor = (type: string) => {
  const colors: Record<string, string> = {
    api: 'blue',
    service: 'green',
    workflow: 'purple',
    rule: 'orange',
  };
  return colors[type] || 'default';
};

const getImplementationLabel = (type: string) => {
  const labels: Record<string, string> = {
    api: 'API调用',
    service: '服务调用',
    workflow: '工作流',
    rule: '规则引擎',
  };
  return labels[type] || type;
};

// 初始化
watch(
  () => props.visible,
  async (newVisible) => {
    if (newVisible && props.resource) {
      try {
        // 加载能力模板
        await loadCapabilityTemplates();

        // 加载RBO相关数据
        await Promise.all([loadEventDefs(), loadBehaviorDefs()]);

        // 从资源数据加载已配置的能力
        if (props.resource.capabilities) {
          try {
            const caps = JSON.parse(props.resource.capabilities);
            configuredCapabilities.value = Object.entries(caps).map(
              ([id, config]: [string, any]) => ({
                id,
                name: getCapabilityName(id),
                description: getCapabilityDescription(id),
                icon: getCapabilityIcon(id),
                type: config.implementation?.type || 'api',
                enabled: config.enabled || true,
                priority: config.priority || 50,
                implementation: config.implementation || {},
                dependencies: config.dependencies || {
                  prerequisites: [],
                  triggers: [],
                },
                // 添加前置约束和SLA配置
                preconditions: config.preconditions || [],
                sla: config.sla || {
                  retry: 1,
                  compensation: '',
                  timeout: 60,
                },
              }),
            );

            // 如果有指定要编辑的能力ID，自动打开配置模态框
            if (props.editCapabilityId) {
              const targetCapability = configuredCapabilities.value.find(
                (cap) => cap.id === props.editCapabilityId,
              );
              if (targetCapability) {
                currentCapability.value = targetCapability;
                configModalVisible.value = true;
                configActiveTab.value = 'basic';
              }
            }
          } catch (error) {
            console.error('Error parsing capabilities:', error);
          }
        }
      } catch (error) {
        console.error('Error loading capability templates:', error);
        message.error('加载能力模板失败，请检查网络连接');
      }
    }
  },
);

const getCapabilityName = (id: string) => {
  const template = [
    ...businessTemplates.value,
    ...technicalTemplates.value,
  ].find((t) => id === t.id || id.startsWith(t.id));
  return template?.name || id;
};

const getCapabilityDescription = (id: string) => {
  const template = [
    ...businessTemplates.value,
    ...technicalTemplates.value,
  ].find((t) => id === t.id || id.startsWith(t.id));
  return template?.description || '';
};

const getCapabilityIcon = (id: string) => {
  const template = [
    ...businessTemplates.value,
    ...technicalTemplates.value,
  ].find((t) => id === t.id || id.startsWith(t.id));
  return template?.icon || 'ant-design:setting-outlined';
};
</script>

<style lang="less" scoped>
.capability-manager-v2 {
  .overview-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 24px;

    .resource-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .resource-icon {
        font-size: 32px;
        color: #1890ff;
      }

      .resource-details {
        h3 {
          margin: 0 0 4px 0;
          color: #333;
        }

        p {
          margin: 0;
          color: #666;
        }
      }
    }

    .capability-stats {
      display: flex;
      gap: 24px;

      .stat-item {
        text-align: center;

        .stat-number {
          font-size: 24px;
          font-weight: bold;
          color: #1890ff;
        }

        .stat-label {
          font-size: 12px;
          color: #666;
        }
      }
    }
  }

  .capability-definition-area {
    display: flex;
    gap: 24px;
    height: 600px;

    .left-panel {
      width: 400px;
      border: 1px solid #e8e8e8;
      border-radius: 8px;
      overflow: hidden;

      .capability-templates {
        height: 100%;

        h4 {
          margin: 0;
          padding: 16px;
          background: #f8f9fa;
          border-bottom: 1px solid #e8e8e8;
        }

        .template-categories {
          height: calc(100% - 60px);
          overflow: hidden;

          :deep(.ant-tabs-content) {
            height: calc(100% - 40px);
            overflow-y: auto;
          }

          .template-list {
            padding: 16px;

            .template-item {
              display: flex;
              align-items: center;
              gap: 12px;
              padding: 12px;
              border: 1px solid #e8e8e8;
              border-radius: 6px;
              margin-bottom: 8px;
              cursor: pointer;
              transition: all 0.3s;

              &:hover {
                border-color: #1890ff;
                background: #f0f8ff;
              }

              .template-icon {
                font-size: 20px;
                color: #1890ff;
              }

              .template-info {
                flex: 1;

                .template-name {
                  font-weight: 500;
                  color: #333;
                }

                .template-desc {
                  font-size: 12px;
                  color: #666;
                  margin-top: 2px;
                }
              }
            }
          }

          .custom-capability-form {
            padding: 16px;
          }
        }
      }
    }

    .right-panel {
      flex: 1;
      border: 1px solid #e8e8e8;
      border-radius: 8px;
      overflow: hidden;

      .configured-capabilities {
        height: 100%;

        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px;
          background: #f8f9fa;
          border-bottom: 1px solid #e8e8e8;

          h4 {
            margin: 0;
          }
        }

        .capabilities-grid {
          height: calc(100% - 60px);
          overflow-y: auto;
          padding: 16px;

          .capability-card {
            border: 1px solid #e8e8e8;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            background: white;
            transition: all 0.3s;

            &:hover {
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            &.disabled {
              opacity: 0.6;
              background: #f5f5f5;
            }

            .capability-header {
              display: flex;
              align-items: center;
              gap: 12px;
              margin-bottom: 12px;

              .capability-icon {
                font-size: 24px;
                color: #1890ff;
              }

              .capability-info {
                flex: 1;

                .capability-name {
                  font-weight: 500;
                  color: #333;
                }

                .capability-type {
                  font-size: 12px;
                  color: #666;
                }
              }

              .capability-actions {
                display: flex;
                align-items: center;
                gap: 8px;
              }
            }

            .capability-config {
              margin-bottom: 12px;

              .config-row {
                display: flex;
                align-items: center;
                gap: 8px;
                margin-bottom: 8px;

                .config-label {
                  font-size: 12px;
                  color: #666;
                  min-width: 60px;
                }
              }
            }

            .capability-description {
              font-size: 12px;
              color: #666;
              line-height: 1.4;
            }
          }
        }

        .empty-state {
          text-align: center;
          padding: 60px 20px;
          color: #666;

          .empty-icon {
            font-size: 48px;
            color: #d9d9d9;
            margin-bottom: 16px;
          }

          p {
            margin: 8px 0;
          }
        }
      }
    }
  }

  .capability-config-form {
    .parameters-config {
      .parameter-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
      }
    }

    .dependencies-config {
      h5 {
        margin: 16px 0 8px 0;
        color: #333;
      }

      .dependency-list {
        margin-bottom: 24px;

        .dependency-item {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;
        }
      }
    }

    .config-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      margin-top: 24px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
    }
  }

  // 前置约束和状态机相关样式
  .preconditions-config {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h4 {
        margin: 0;
      }
    }

    .precondition-item {
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      padding: 16px;
      margin-bottom: 12px;

      .precondition-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
      }
    }
  }

  .sla-config {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;

    h4 {
      margin-bottom: 16px;
    }
  }

  .state-machine-config {
    .current-state {
      margin-bottom: 24px;
    }

    .allowed-transitions {
      margin-bottom: 24px;

      .transition-item {
        margin-bottom: 8px;
      }
    }

    .transition-definition {
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      padding: 12px;
      margin-bottom: 8px;
    }
  }

  // 事件系统相关样式
  .events-config {
    .event-definitions {
      margin-bottom: 24px;

      .event-definition {
        border: 1px solid #f0f0f0;
        border-radius: 6px;
        padding: 16px;
        margin-bottom: 12px;

        .event-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .event-channel {
            font-size: 12px;
            color: #666;
          }
        }

        .event-schema {
          h5 {
            margin-bottom: 8px;
          }

          pre {
            background: #f5f5f5;
            padding: 8px;
            border-radius: 4px;
            font-size: 12px;
            overflow-x: auto;
          }
        }
      }
    }

    .event-subscriptions {
      margin-bottom: 24px;

      .subscription-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;
      }
    }

    .event-publishing {
      border-top: 1px solid #f0f0f0;
      padding-top: 16px;
    }
  }

  // 行为执行相关样式
  .behaviors-config {
    .behaviors-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h4 {
        margin: 0;
      }

      .behaviors-actions {
        display: flex;
        gap: 8px;
      }
    }

    .behavior-list {
      .behavior-item {
        border: 1px solid #f0f0f0;
        border-radius: 6px;
        padding: 16px;
        margin-bottom: 12px;

        .behavior-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          h5 {
            margin: 0;
          }
        }

        .behavior-details {
          p {
            margin-bottom: 12px;
            color: #666;
          }

          .behavior-actions {
            display: flex;
            gap: 8px;
          }
        }
      }
    }
  }

  // 行为执行模态框样式
  .behavior-execution-form {
    .behavior-info {
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;

      h4 {
        margin-bottom: 8px;
      }

      p {
        color: #666;
        margin: 0;
      }
    }

    .execution-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      margin-top: 24px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
    }
  }

  // 状态历史相关样式
  .state-history-modal {
    .empty-state {
      text-align: center;
      padding: 40px 20px;
      color: #666;
    }

    .history-list {
      .history-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .history-state {
          margin-right: 16px;
        }

        .history-info {
          flex: 1;

          .history-time {
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;
          }

          .history-reason {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
  }
}
</style>
